function broadcast(componentName, eventName, params) {
  const children = this.$children || []

  // dfs
  children.forEach((child) => {
    const name = child.$options.componentName || child.$options.name
    if (name === componentName) {
      child.$emit.apply(child, [eventName].concat(params))
      return
    }

    broadcast.call(child, componentName, eventName, params)
  })
}

export default {
  methods: {
    // 广播
    broadcast,
    // 派发
    dispatch(componentName, eventName, params) {
      let parent = this.$parent || this.$root
      let name = parent.$options.componentName || parent.$options.name

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent
        if (parent) {
          name = parent.$options.componentName || parent.$options.name
        }
      }

      if (parent) {
        parent.$emit.apply(parent, [eventName].concat(params))
      }
    }
  }
}
